<?php declare(strict_types=1);

namespace Distributed\Dispatcher;

use Swoole\Server;
use Communication\TxSocketData;
use Distributed\EventMap;
use Distributed\Contract\IEvent;

/**
 * 分发处理
 * @author mg
 */
class Dispatcher
{
	
	/**
	 * 
	 * @var Server
	 */
	private static $server;
	
	private function __construct(Server $server)
	{
		static::$server = $server;
	}
	
	public static function getInstance(Server $server): self
	{
		if (!static::$server) {
			static::$server = new static($server);
		}
		
		return static::$server;
	}
	
	/**
	 * 接收
	 * @param  [type] $serv    [description]
	 * @param  [type] $fd      [description]
	 * @param  [type] $from_id [description]
	 * @param  [type] $data    [description]
	 * @return [type]          [description]
	 */
	public function dealReceive(int $fd, int $from_id, string $data){
		
		$data = TxSocketData::fromMsg($data);
		
		
		$event = EventMap::EVENT_MAP[$data->action];
		return $this->dispatcherData(new $event($data), $fd);
		
	}
	
	public function dispatcherData(IEvent $event, int $fd)
	{
		
		return $event->parseEvent($fd);
		
	}
}